// ==UserScript==
// @name         飞瓜数据抓取
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  just temporary code...
// @author       nobody
// @match        http://118.178.120.247:7676/Member
// @require      https://cdn.bootcdn.net/ajax/libs/xlsx/0.18.5/xlsx.core.min.js
// @icon         https://www.google.com/s2/favicons?sz=64&domain=120.247
// @grant        none
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';
    var params = null;
    var $ = window.$;
    var jqueryPost = $.post;
    var initalExportBtn = function(){
        $('#ConditionsDiv').before('<div class="industry-items" style="margin-top: 10px;"><button id="diy-export-data-btn">导出数据</button><span style="margin-left: 12px; color: #c43100; display: none;">正在导出页数：<span id="diy-export-page">1</span></span></div>');
        var XLSX = window.XLSX;
        // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
        function sheet2blob(sheet, sheetName) {
            sheetName = sheetName || 'sheet1';
            var workbook = {
                SheetNames: [sheetName],
                Sheets: {}
            };
            workbook.Sheets[sheetName] = sheet;
            // 生成excel的配置项
            var wopts = {
                bookType: 'xlsx', // 要生成的文件类型
                bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                type: 'binary'
            };
            var wbout = XLSX.write(workbook, wopts);
            var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
            // 字符串转ArrayBuffer
            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }
            return blob;
        }
        /**
         * 通用的打开下载对话框方法，没有测试过具体兼容性
         * @param url 下载地址，也可以是一个blob对象，必选
         * @param saveName 保存文件名，可选
         */
        function openDownloadDialog(url, saveName){
            if(typeof url == 'object' && url instanceof Blob)
            {
                url = URL.createObjectURL(url); // 创建blob地址
            }
            var aLink = document.createElement('a');
            aLink.href = url;
            aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
            var event;
            if(window.MouseEvent) event = new MouseEvent('click');
            else
            {
                event = document.createEvent('MouseEvents');
                event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            }
            aLink.dispatchEvent(event);
        }
        // 请求并解析数据
        function requestAndParse(result, page, postFun, finalFun) {
            params.page = page;
            $('#diy-export-page').html(page + ' ...');
            postFun("/BloggerSearch/Search", params, function (resp) {
                var dataElems = $(resp).find('div[class="v-search-item v3-search-item"]');
                for (var i = 0; i < dataElems.length; i++) {
                    var dataElem = $(dataElems[i]);
                    var title = dataElem.find('a[class="nickname"]').text().trim();
                    var douyinId = dataElem.find('dl>dd:eq(1) span').text().trim().substring(5);
                    var explain = dataElem.find('dl>dd:eq(3)').text().trim().substring(3);
                    var tagVals = [];
                    var tagElems = dataElem.find('dl>dd:eq(2) span[class="tag-content-label-1"]');
                    for (var j = 0; j < tagElems.length; j++) {
                        tagVals.push($(tagElems[j]).text().trim());
                    }
                    var dataItem = [
                        title,
                        douyinId,
                        tagVals.join(';'),
                        explain
                    ];
                    var countElems = dataElem.find('ul>li span[class="number"]');
                    for (var z = 0; z < countElems.length; z++) {
                        dataItem.push($(countElems[z]).text().trim());
                    }
                    result.push(dataItem);
                }
            });
            if (page < 100) {
                setTimeout(function() {
                    requestAndParse(result, page + 1, postFun, finalFun)
                }, 689);
            } else {
                finalFun();
            }
        }
        $('#diy-export-data-btn').click(function(){
            if (!params) {
                alert('至少要查询一次才能导出');
                return;
            }
            var result = [["名称", "抖音ID", "标签", "简介", "总粉丝", "30天粉丝增量", "30天作品数", "30天总点赞增量", "视频平均点赞", "30天带货视频数", "30天带货视频销量"]];
            $('#diy-export-page').parent().show();
            requestAndParse(result, 1, jqueryPost, function() {
                var sheet = XLSX.utils.aoa_to_sheet(result);
                openDownloadDialog(sheet2blob(sheet), '数据导出.xlsx');
                $('#diy-export-page').parent().hide();
            });
        });
    };
    var initial = true;
    $.post = function(url, data, callback, type){
        // 通过截断获取请求参数
        jqueryPost(url, data, callback, type);
        if (url == '/BloggerSearch/Search') {
            params = data;
            if (initial) {
                initial = false;
                initalExportBtn();
            }
        }
    }
})();